<?php
declare(strict_types=1);

namespace Service\FileService;
use Service\BaseService;
use Service\Code\Normal;

/**
 * 本地文件上传资源
 */
class FileLocalService extends BaseService
{
    /**
     * 上传文件
     * @param string $type
     * @param $file
     */
    public function upload(string $type = null,$fileObject = NULL)
    {
        if( empty($type) ) {
            return Normal::returnCode(Normal::FAIL,"上传文件模块type不能为空");
        }
        
        if( empty($fileObject) ) {
            return Normal::returnCode(Normal::FAIL,"上传文件file不能为空");
        }
        
        $ext = $fileObject->getExtension();
        $upLoadPath = 'uploads'.DIRECTORY_SEPARATOR.$type.DIRECTORY_SEPARATOR;
        $filePath = BASE_PATH.DIRECTORY_SEPARATOR.$upLoadPath;
        if( !is_dir($filePath) ) {
            mkdir($filePath, 0777, true);
        }
        
        chmod($filePath, 0777);
        $fileName = date("YmdHis")."_".uniqid()."_".rand(100000,999999).".".$ext;
        $fileObject->moveTo($filePath.$fileName);
        if ($fileObject->isMoved()) {
            return Normal::returnCode(Normal::SUC,"上传成功",[
                'fileName'          => $upLoadPath.$fileName,
                'originFileName'    => $fileObject->getClientFilename(),
                "desc"              => "描述fileName作为后端websocket需要传入的fileUrl地址，originFileName为原始上传文件名称"
            ]);
        }
        return Normal::returnCode(Normal::FAIL,"上传失败");
    }
}